package com.jinglin.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Constants;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jinglin.component.EsSearchComponent;
import com.jinglin.entity.enums.PageSize;
import com.jinglin.entity.enums.ResponseCodeEnum;
import com.jinglin.entity.enums.SearchOrderTypeEnum;
import com.jinglin.entity.po.UserAction;
import com.jinglin.entity.po.VideoDanmu;
import com.jinglin.entity.po.VideoInfo;
import com.jinglin.entity.query.SimplePage;
import com.jinglin.entity.vo.PaginationResultVO;
import com.jinglin.exception.BusinessException;
import com.jinglin.mapper.VideoDanmuMapper;
import com.jinglin.mapper.VideoInfoMapper;
import com.jinglin.service.VideoDanmuService;
import com.jinglin.service.VideoInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * <p>
 * 视频弹幕 服务实现类
 * </p>
 *
 * @author ${author}
 * @since 2025-03-24
 */
@Service
public class VideoDanmuServiceImpl extends ServiceImpl<VideoDanmuMapper, VideoDanmu> implements VideoDanmuService {
    @Autowired
    private VideoInfoService videoInfoService;
    @Autowired
    private VideoInfoMapper videoInfoMapper;
    @Autowired
    private VideoDanmuMapper videoDanmuMapper;
/*    @Autowired
    private EsSearchComponent esSearchComponent;*/
    @Override
    @Transactional
    public void saveVideoDanmu(VideoDanmu videoDanmu) {
        VideoInfo videoInfo = videoInfoService.getById(videoDanmu.getVideoId());
        if (videoInfo == null){
            throw new BusinessException(ResponseCodeEnum.CODE_600);
        }
        if (videoInfo.getInteraction() != null && videoInfo.getInteraction().contains(Constants.ZERO.toString())) {
            throw new BusinessException("UP主已经关闭弹幕");
        }
        this.save(videoDanmu);
        // 更新弹幕数
        videoInfoMapper.updateCountInfo("danmu_count",1,videoInfo.getVideoId());
/*        //在ES更新弹幕数
        esSearchComponent.updateDocCount(videoDanmu.getVideoId(), SearchOrderTypeEnum.VIDEO_DANMU.getField(), 1);*/

    }

    @Override
    public PaginationResultVO loadDanmuManage(String videoId, Integer pageNo, Integer pageSize, String userId,String videoNameFuzzy) {
        // 查出当前用户所属视频的所有弹幕数量。
        int count = videoDanmuMapper.countWithAllVideo(userId,videoNameFuzzy);
        pageSize = pageSize == null ? PageSize.SIZE15.getSize() : pageSize;

        SimplePage page = new SimplePage(pageNo, count, pageSize);
        List<VideoDanmu> list = videoDanmuMapper.listWithAllVideo(page.getStart(),page.getPageSize(),userId,videoNameFuzzy,videoId);

        PaginationResultVO<UserAction> result = new PaginationResultVO(count, page.getPageSize(), page.getPageNo(), page.getPageTotal(), list);

        return result;


    }
}
